package com.mason.forum.service.impl;

import com.mason.forum.common.ResultCode;
import com.mason.forum.dao.MessageMapper;
import com.mason.forum.exception.ApplicationException;
import com.mason.forum.model.Message;
import com.mason.forum.model.User;
import com.mason.forum.model.vo.MessageVO;
import com.mason.forum.service.IMessageService;
import com.mason.forum.service.IUserService;
import com.mason.forum.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-10-08
 * Time: 19:49
 */

@Slf4j
@Service
public class MessageServiceImpl implements IMessageService {


    @Resource
    private MessageMapper messageMapper;

    @Resource
    private IUserService userService;

    @Override
    public void sendMessage(Message message) {
        // 参数校验
        Long postUserId = message.getPostUserId();//发送者id
        Long receiveUserId = message.getReceiveUserId();//接收者id
        if(postUserId == null || postUserId <= 0
                || receiveUserId == null || receiveUserId <= 0
                || !StringUtils.hasLength(message.getContent())) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        // 接收者用户得存在（接收者禁言也没事） receiveUser
        User receiveUser = userService.selectById(receiveUserId);
        if(receiveUser == null || receiveUser.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + " receiveUser id：" + receiveUserId);
            throw new ApplicationException(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        // 发送者状态得正常 postUser
        User postUser = userService.selectById(postUserId);
        if(postUser == null || postUser.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + " postUser id：" + postUserId);
            throw new ApplicationException(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        if(postUser.getState() == 1) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString() + " postUser id：" + postUserId);
            throw new ApplicationException(ResultCode.FAILED_USER_BANNED);
        }
        // 不能发送给自己
        if(postUserId.equals(receiveUserId)) {
            log.warn(ResultCode.FAILED_CANNOT_SEND_TO_SELF.toString() + " user id：" + postUserId);
            throw new ApplicationException(ResultCode.FAILED_CANNOT_SEND_TO_SELF);
        }
        // 设置默认值
        Date date = new Date();
        message.setCreateTime(date);
        message.setUpdateTime(date);
        message.setDeleteState((byte) 0);
        message.setState((byte) 0);
        // dao层 - 写入数据库
        int rows = messageMapper.insertSelective(message);
        if(rows != 1) {
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(ResultCode.FAILED_CREATE);
        }
        // 新增成功
        log.info(ResultCode.SUCCESS.toString() + "新增成功: message id: "
                + message.getId() + ". ");
    }

    @Override
    public Long getNotAwareNumber(Long receiveUserId) {
        // 校验参数
        if(receiveUserId == null || receiveUserId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        // 接收者用户得存在（接收者禁言也没事） postUser
        User receiveUser = userService.selectById(receiveUserId);
        if(receiveUser == null || receiveUser.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + " receiveUser id：" + receiveUserId);
            throw new ApplicationException(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        // dao层 - 获取未读私信数
        Long number = messageMapper.getNotAwareNumber(receiveUserId);
        if(number == null) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(ResultCode.ERROR_SERVICES);
        }
        // 成功返回
        return number;
    }

    @Override
    public Message selectById(Long id) {
        // 校验参数
        if(id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        // dao层
        Message message = messageMapper.selectByPrimaryKey(id);
        if(message == null || message.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_MESSAGE_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        // 成功返回
        return message;
    }

    @Override
    public List<MessageVO> getMessagesById(Long receiveUserId) {
        // 校验参数
        if(receiveUserId == null || receiveUserId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        // 接收者用户得存在（接收者禁言也没事） postUser
        User receiveUser = userService.selectById(receiveUserId);
        if(receiveUser == null || receiveUser.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + " receiveUser id：" + receiveUserId);
            throw new ApplicationException(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        // dao层 - 获得私信列表
        List<MessageVO> messageVOS = messageMapper.getMessagesById(receiveUserId);
        // 直接返回
        return messageVOS;
    }

    @Override
    public void markRead(Long id, Byte state) {
        // 校验参数
        if(id == null || id <= 0 || state == null || state < 0 || state > 2) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        // 这个站内信必须存在
        Message message = messageMapper.selectByPrimaryKey(id);
        if(message == null || message.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_MESSAGE_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        // 构造修改对象
        Message updateMessage = new Message();
        updateMessage.setState(state);
        updateMessage.setId(id);//设置主键
        // dao层 - 标记修改
        int rows = messageMapper.updateByPrimaryKeySelective(updateMessage);
        if(rows != 1) {
            log.warn(ResultCode.FAILED_MESSAGE_UPDATE_STATE.toString());
            throw new ApplicationException(ResultCode.FAILED_MESSAGE_UPDATE_STATE);
        }
        // 修改成功
        log.info(ResultCode.SUCCESS.toString() + "更新成功: message id: "
                + id + ". ");
    }

    @Override
    public void replyMessage(Message message, Long id) {
        // 1. 发送消息
        sendMessage(message);
        // 2. 标记修改
        markRead(id, (byte) 2);
        // 3. 回复成功
        log.info(ResultCode.SUCCESS.toString() + "回复成功: 被回复站内信 id: "
                + id + ". ");
    }
}
